package samsung.sds.system.security.service.impl;

import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;

import samsung.sds.systemMonitor.userOperationMonitor.service.UserOperationMonitorService;

@Service("sysAccessDecisionManager")
public class SysAccessDecisionManager implements AccessDecisionManager {

	@Autowired
	private UserOperationMonitorService userOperationMonitorServiceImpl;

	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (configAttributes == null) {
			return;
		}
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();
		while (iterator.hasNext()) {
			ConfigAttribute configAttribute = iterator.next();
			String needPermission = configAttribute.getAttribute();
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needPermission.equals(ga.getAuthority())) {
					return;
				}
			}
		}
		// 调用日志接口记录非法访问资源信息
		try {
			insertIllegalAccessMessage(authentication, object);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		throw new AccessDeniedException(" 没有权限访问");
	}

	/**
	 * 调用日志接口记录非法访问资源信息
	 * 
	 * @param authentication
	 * @param object
	 * @throws UnknownHostException
	 */
	private void insertIllegalAccessMessage(Authentication authentication,
			Object object) throws UnknownHostException {
		String userName = "";
		if (authentication.getPrincipal() instanceof String) {
			userName = "anonymousUser";
		} else {
			UserDetails user = (UserDetails) authentication.getPrincipal();
			userName = user.getUsername();
		}
		FilterInvocation filterInvocation = (FilterInvocation) object;
		HttpServletRequest request = filterInvocation.getHttpRequest();
		String servletPath = request.getServletPath();
		userOperationMonitorServiceImpl.insertAttackOperationInfo(request,
				userName, servletPath);
	}

	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

}
